package com.god.gl.ble.test;

import android.Manifest;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.god.gl.ble.R;
import com.god.gl.ble.adapter.MyBluetoothAdapter;
import com.god.gl.ble.utils.HidConncetUtil;
import com.njzdr.common.BluetoothManager;
import com.njzdr.common.BluetoothScanListner;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @author gl
 * @date 2021/1/25
 * @desc
 */
public class BlueActivity extends AppCompatActivity {

    private static final String TAG = "BlueActivity";
    private BluetoothAdapter mBluetoothAdapter;
    private HidConncetUtil mHidConncetUtil;
    private BlueBroadcastReceiver mBlueBroadcastReceiver;
    private MyBluetoothAdapter mMyBluetoothAdapter;
    private ListView mListView;
    private static final int REQUEST_CODE_OPEN_GPS = 1;
    private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
    private TextView tvBluetoothState;

    public static void startActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, BlueActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blue);
        checkPermissions();
        initview();
        initBlue();
        //初始化已连接hid列表
        initPair();
    }

    private void initview() {
        mListView = (ListView) findViewById(R.id.listview);
        tvBluetoothState = findViewById(R.id.tv_bluetooth_state);

        //仅搜索BLE蓝牙
        findViewById(R.id.ble_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BluetoothManager.getInstance().bleScan(new BluetoothScanListner() {
                    @Override
                    public void scanStart(boolean isSuccess) {
                        tvBluetoothState.setVisibility(View.VISIBLE);
                        tvBluetoothState.setText("开始搜索蓝牙");
                    }

                    @Override
                    public void scanResult(BluetoothDevice device) {
                        tvBluetoothState.setText("蓝牙搜索中***");
                    }

                    @Override
                    public void scanResult(List<BluetoothDevice> deviceList) {
                        mMyBluetoothAdapter.setData(deviceList);
                        mMyBluetoothAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void scanFinish() {
                        tvBluetoothState.setText("蓝牙搜索结束");
                        tvBluetoothState.setVisibility(View.GONE);
                    }
                });
            }
        });

        //搜索BLE和经典蓝牙
        Button search = (Button) findViewById(R.id.search);
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BluetoothManager.getInstance().scan(new BluetoothScanListner() {
                    @Override
                    public void scanStart(boolean isSuccess) {
                        tvBluetoothState.setVisibility(View.VISIBLE);
                        tvBluetoothState.setText("开始搜索蓝牙");
                    }

                    @Override
                    public void scanResult(BluetoothDevice device) {
                        tvBluetoothState.setText("蓝牙搜索中***");
                    }

                    @Override
                    public void scanResult(List<BluetoothDevice> deviceList) {
                        mMyBluetoothAdapter.setData(deviceList);
                        mMyBluetoothAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void scanFinish() {
                        tvBluetoothState.setText("蓝牙搜索结束");
                        tvBluetoothState.setVisibility(View.GONE);
                    }
                });

               /* //扫描蓝牙设备
                ScanSettings.Builder builder = new ScanSettings.Builder();
                //设置高功耗模式
                builder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);
                //android 6.0添加设置回调类型、匹配模式等
                if (android.os.Build.VERSION.SDK_INT >= 23) {
                    //定义回调类型
                    builder.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES);
                    //设置蓝牙LE扫描滤波器硬件匹配的匹配模式
                    builder.setMatchMode(ScanSettings.MATCH_MODE_STICKY);
                }
                //芯片组支持批处理芯片上的扫描
                if (mBluetoothAdapter.isOffloadedScanBatchingSupported()) {
                    //设置蓝牙LE扫描的报告延迟的时间（以毫秒为单位）
                    //设置为0以立即通知结果
                    builder.setReportDelay(0L);
                }

                Map<String, BluetoothDevice> bluetoothDeviceMap = new ArrayMap<>();

                BluetoothLeScanner bluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
                if (!mBluetoothAdapter.isDiscovering()) {
//                    mBluetoothAdapter.startDiscovery();
                    ScanFilter.Builder scanFilter = new ScanFilter.Builder();
                    List<ScanFilter> scanFilters = new ArrayList<>();
                    scanFilters.add(scanFilter.build());
                    bluetoothLeScanner.startScan(new ScanCallback() {
                        @Override
                        public void onScanResult(int callbackType, ScanResult result) {
                            super.onScanResult(callbackType, result);
                            BluetoothDevice device = result.getDevice();
                            if (mMyBluetoothAdapter == null) {
                                mMyBluetoothAdapter = new MyBluetoothAdapter(BlueActivity.this);
                                mListView.setAdapter(mMyBluetoothAdapter);
                            }
                            if (!bluetoothDeviceMap.containsKey(device.getAddress())) {
//                                bluetoothDeviceMap.put(device.getAddress(), device);
                                mMyBluetoothAdapter.addData(device);
                                mMyBluetoothAdapter.notifyDataSetChanged();
                            }
                        }
                    });
                }*/
            }
        });
    }

    private void initPair() {
        //得到已经配对的列表
        List<BluetoothDevice> pairDeviceList = BluetoothManager.getInstance().getPairDeviceList();

        if (mMyBluetoothAdapter == null) {
            mMyBluetoothAdapter = new MyBluetoothAdapter(BlueActivity.this);
            mListView.setAdapter(mMyBluetoothAdapter);
        }
        mMyBluetoothAdapter.setData(pairDeviceList);
        mMyBluetoothAdapter.notifyDataSetChanged();
    }

    private void initBlue() {
        //初始化广播接收
        BluetoothManager.getInstance().registerBoradcastReceiver(this);

        if (!BluetoothManager.getInstance().isAdapterReady()) {
            BluetoothManager.getInstance().openBluetooth(this);
        }

        //4.0以上才支持HID模式
        if (Build.VERSION.SDK_INT >= 14) {
            this.mHidConncetUtil = new HidConncetUtil(this);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        BluetoothManager.getInstance().unregisterReceiver(this);
    }


    public void registerReceiver() {
        IntentFilter localIntentFilter = new IntentFilter();
        localIntentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        localIntentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        localIntentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        localIntentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
        localIntentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        localIntentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        localIntentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        //   localIntentFilter.addAction("android.bluetooth.input.profile.action.CONNECTION_STATE_CHANGED");
        this.registerReceiver(mBlueBroadcastReceiver, localIntentFilter);
    }

    private class BlueBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String str = intent.getAction();
            Log.e(TAG, "onReceive" + str);
            //通过广播接收到了BluetoothDevice
            final BluetoothDevice localBluetoothDevice = (BluetoothDevice) intent
                    .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (localBluetoothDevice != null) {
                Log.e(TAG, localBluetoothDevice.getName() + "=======" + localBluetoothDevice.getAddress());
                if (mMyBluetoothAdapter == null) {
                    mMyBluetoothAdapter = new MyBluetoothAdapter(BlueActivity.this);
                    mListView.setAdapter(mMyBluetoothAdapter);
                }
                mMyBluetoothAdapter.addData(localBluetoothDevice);
                mMyBluetoothAdapter.notifyDataSetChanged();
            }
        }
    }


    private void checkPermissions() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            Toast.makeText(this, getString(R.string.please_open_blue), Toast.LENGTH_LONG).show();
            return;
        }

        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH
                , Manifest.permission.ACCESS_COARSE_LOCATION};
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                Log.d("permission", "权限申请成功");
//                onPermissionGranted(permission);
            } else {
                permissionDeniedList.add(permission);
                onPermissionGranted(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
        }
    }

    private void onPermissionGranted(String permission) {
        switch (permission) {
            case Manifest.permission.ACCESS_FINE_LOCATION:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M /*&& !checkGPSIsOpen()*/) {
                    new AlertDialog.Builder(this)
                            .setTitle(R.string.notifyTitle)
                            .setMessage(R.string.gpsNotifyMsg)
                            .setNegativeButton(R.string.cancel,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            finish();
                                        }
                                    })
                            .setPositiveButton(R.string.setting,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                            startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
                                        }
                                    })

                            .setCancelable(false)
                            .show();
                }
                break;
        }
    }

    private boolean checkGPSIsOpen() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null)
            return false;
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_OPEN_GPS) {
            if (checkGPSIsOpen()) {

            }
        } else if (requestCode == BluetoothManager.REQUEST_ENABLE_BT) {
            //蓝牙开启成功
            Toast.makeText(this, "蓝牙开启成功", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.e("keyCode", keyCode + "");
        return super.onKeyDown(keyCode, event);
    }


}
